######## REPLICATION CODE FOR DOST, ENOS, HOCHSCHILD: PSQ 2020, ONLINE APPENDIX C ########

#### SET-UP ####
## set working directory
setwd("data and replication")
## load packages
library(descr)
library(ggplot2)
library(survey)
library(gridExtra)
library(scales)
library(dotwhisker)
## load data
# 2017 data set
d17 <- read.csv("cleaned_datasets/harris_dec2017.csv")


#### FIGURE H and FIGURE I ####
## calculations prior to figure creation 
t <- crosstab(d17$ideo, d17$stay_leave, prop.c=T, plot=F, weight=d17$weight)
t2 <- crosstab(d17$ptystr, d17$stay_leave, prop.c=T, plot=F, weight=d17$weight)
t3 <- crosstab(d17$agerec, d17$stay_leave, prop.c=T, plot=F, weight=d17$weight)
t4 <- crosstab(d17$increc_4, d17$stay_leave, prop.c=T, plot=F, weight=d17$weight)
t5 <- crosstab(d17$male, d17$stay_leave, prop.c=T, plot=F, weight=d17$weight)
t6 <- crosstab(d17$racerec, d17$stay_leave, prop.c=T, plot=F, weight=d17$weight)
t7 <- crosstab(d17$educ, d17$stay_leave, prop.c=T, plot=F, weight=d17$weight)
t8 <- crosstab(d17$employ, d17$stay_leave, prop.c=T, plot=F, weight=d17$weight)
t9 <- crosstab(d17$QD16, d17$stay_leave, prop.c=T, plot=F, weight=d17$weight) # with QD16 values: 1=urban;2=suburban;3=rural
df1 <- data.frame((t$prop.col)*100)
names(df1) <- c("demo","TG","TG_freq")
df1$demo <- car::recode(df1$demo, "1='Strong Liberal';2='Lean Liberal';3='Moderate';4='Lean Conserv';5='Strong Conserv'")
df1$col <- 8
df2 <- data.frame((t2$prop.col)*100)
names(df2) <- c("demo","TG","TG_freq")
df2$demo <- car::recode(df2$demo, "1='Strong Rep';2='Not Strong Rep';3='Lean Rep';4='Pure Ind';5='Lean Dem';6='Not Strong Dem';7='Strong Dem'")
df2$col <- 9
df3 <- data.frame((t3$prop.col)*100)
names(df3) <- c("demo","TG","TG_freq")
df3$demo <- car::recode(df3$demo, "1='18-29';2='30-49';3='50-64';4='65+'")
df3$col <- 3
df4 <- data.frame((t4$prop.col)*100)
names(df4) <- c("demo","TG","TG_freq")
df4$demo <- car::recode(df4$demo, "1='Income <$35K';2='Income $35-75K';3='Income $75-125K';4='Income $125K+'")
df4$col <- 5
df5 <- data.frame((t5$prop.col)*100)
names(df5) <- c("demo","TG","TG_freq")
df5$demo <- car::recode(df5$demo, "1='Men';0='Women'")
df5$col <- 1
df6 <- data.frame((t6$prop.col)*100)
names(df6) <- c("demo","TG","TG_freq")
df6$demo <- car::recode(df6$demo, "1='White NH';2='Black NH';3='Hispanic';4='Other NH'")
df6$col <- 2
df7 <- data.frame((t7$prop.col)*100)
names(df7) <- c("demo","TG","TG_freq")
df7$demo <- car::recode(df7$demo, "1='HS or less';2='Some college';3='College grad';4='Post grad'")
df7$col <- 4
df8 <- data.frame((t8$prop.col)*100)
names(df8) <- c("demo","TG","TG_freq")
df8$demo <- car::recode(df8$demo, "1='Employed full-time';2='Employed part-time';3='Not employed, not looking';4='Not employed, looking'")
df8$col <- 6
df9 <- data.frame((t9$prop.col)*100)
names(df9) <- c("demo","TG","TG_freq")
df9$demo <- car::recode(df9$demo, "1='Urban';2='Suburban';3='Rural'")
df9$col <- 7
df <- rbind.data.frame(df1,df2,df3,df4,df5,df6,df7,df8,df9)
df$TG <- as.numeric(as.character(df$TG))
df <- subset(df, TG<=4)
df$demo <- factor(df$demo,levels = c("Men","Women",paste(unique(df6$demo)),paste(unique(df3$demo)),
                                     paste(unique(df7$demo)),paste(unique(df4$demo)),
                                     paste(unique(df8$demo)),paste(unique(df9$demo)),"Strong Conserv",
                                     "Lean Conserv","Moderate","Lean Liberal","Strong Liberal",
                                     paste(unique(df2$demo))))
rm(df1,df2,df3,df4,df5,df6,df7,df8,df9,t,t2,t3,t4,t5,t6,t7,t8,t9)
# getting standard errors
dsgn <- svydesign(ids = ~RESPID, weights = ~weight, data = subset(d17, stay_leave<=4)) 
df.se <- data.frame(matrix(c(rep(1,4),rep(2,4),rep(3,4),rep(4,4),rep(5,4),rep(6,4),rep(7,4),rep(8,4),rep(9,4),
                             rep(1:4,9),rep(NA,36)),ncol=3,nrow=length(unique(df$col))*4))
names(df.se) <- c("col","TG","sd")
df.se[1:4,3] <- svyby(~male, ~stay_leave,dsgn, svymean)[,3]
df.se[5:8,3] <- svyby(~racerec, ~stay_leave,dsgn, svymean)[,3]
df.se[9:12,3] <- svyby(~agerec, ~stay_leave,dsgn, svymean)[,3]
df.se[13:16,3] <- svyby(~educ, ~stay_leave,dsgn, svymean)[,3]
df.se[17:20,3] <- svyby(~increc_4, ~stay_leave,dsgn, svymean,na.rm=T)[,3]
df.se[21:24,3] <- svyby(~employ, ~stay_leave,dsgn, svymean,na.rm=T)[,3]
df.se[25:28,3] <- svyby(~QD16, ~stay_leave,dsgn, svymean,na.rm=T)[,3]
df.se[29:32,3] <- svyby(~ideo, ~stay_leave,dsgn, svymean)[,3]
df.se[33:36,3] <- svyby(~ptystr, ~stay_leave,dsgn, svymean,na.rm=T)[,3]
df <- merge(df, df.se, by = c("col","TG"))
df$sd <- df$sd*100
# subsetting into groups
df_stay <- subset(df, TG==1)
df_leave <- subset(df, TG==2)
df_join <- subset(df, TG==3)
df_never <- subset(df, TG==4)
rm(df, df.se)
### creating individual plots for each Loyalist/Switcher group for Figure H
my.palette <- c("#8DD3C7","#FFFFB3","#BEBADA","#FB8072","#80B1D3","#FDB462","#B3DE69","#FF99CC","#BC80BD")
## Republican Loyalists plot
p1 <- ggplot(df_stay, aes(x=factor(demo, levels = rev(levels(factor(demo)))), y=TG_freq, fill = factor(col))) + 
  geom_bar(stat = "identity") + geom_text(aes(y=TG_freq/2, label=round(TG_freq)), color="black", size=2.5) +
  geom_errorbar(aes(ymin=TG_freq-sd, ymax=TG_freq+sd), width=.5) +
  scale_fill_manual(values = my.palette) + theme(legend.position="none",axis.ticks.y = element_blank()) + ylab("tk") + xlab("") +
  ggtitle("Republican Loyalists") + coord_flip() + theme(plot.title = element_text(size=10), axis.text = element_text(size=8), axis.title = element_text(color="white")) +
  scale_x_discrete(limits = c(levels(df_stay$demo)[37:31],"b8",levels(df_stay$demo)[30:26],"b7",
                              levels(df_stay$demo)[25:23],"b6",levels(df_stay$demo)[22:19],"b5",
                              levels(df_stay$demo)[18:15],"b4",levels(df_stay$demo)[14:11],"b3",
                              levels(df_stay$demo)[10:7],"b2",levels(df_stay$demo)[6:3],"b1",
                              levels(df_stay$demo)[2:1]),
                   labels=c("b8"="","b7"="","b6"="","b5"="","b4"="","b3"="","b2"="","b1"="")) +
  scale_y_continuous(breaks=c(0,25,50,75,100), limits = c(-25,100)) 
## Republican Switchers plot
p2 <- ggplot(df_leave, aes(x=factor(demo, levels = rev(levels(factor(demo)))), y=TG_freq, fill = factor(col))) + 
  geom_bar(stat = "identity") + geom_text(aes(y=TG_freq/2, label=round(TG_freq)), color="black", size=2.5) +
  geom_errorbar(aes(ymin=TG_freq-sd, ymax=TG_freq+sd), width=.5) +
  scale_fill_manual(values = my.palette) + theme(legend.position="none",axis.ticks.y = element_blank()) + ylab("tk") + xlab("") +
  ggtitle("Republican Switchers") + coord_flip() + theme(plot.title = element_text(size=10), axis.text = element_text(size=8), axis.title = element_text(color="white")) +
  scale_x_discrete(limits = c(levels(df_stay$demo)[37:31],"b8",levels(df_stay$demo)[30:26],"b7",
                              levels(df_stay$demo)[25:23],"b6",levels(df_stay$demo)[22:19],"b5",
                              levels(df_stay$demo)[18:15],"b4",levels(df_stay$demo)[14:11],"b3",
                              levels(df_stay$demo)[10:7],"b2",levels(df_stay$demo)[6:3],"b1",
                              levels(df_stay$demo)[2:1]),
                   labels=c("b8"="","b7"="","b6"="","b5"="","b4"="","b3"="","b2"="","b1"="")) +
  scale_y_continuous(breaks=c(0,25,50,75,100), limits = c(-25,100)) 
## Democratic Switchers plot
p3 <- ggplot(df_join, aes(x=factor(demo, levels = rev(levels(factor(demo)))), y=TG_freq, fill = factor(col))) + 
  geom_bar(stat = "identity") + geom_text(aes(y=TG_freq/2, label=round(TG_freq)), color="black", size=2.5) +
  geom_errorbar(aes(ymin=TG_freq-sd, ymax=TG_freq+sd), width=.5) +
  scale_fill_manual(values = my.palette) + theme(legend.position="none",axis.ticks.y = element_blank()) + ylab("% identifying as each") + xlab("") +
  ggtitle("Democratic Switchers") + coord_flip() + theme(plot.title = element_text(size=10), axis.text = element_text(size=8)) +
  scale_x_discrete(limits = c(levels(df_stay$demo)[37:31],"b8",levels(df_stay$demo)[30:26],"b7",
                              levels(df_stay$demo)[25:23],"b6",levels(df_stay$demo)[22:19],"b5",
                              levels(df_stay$demo)[18:15],"b4",levels(df_stay$demo)[14:11],"b3",
                              levels(df_stay$demo)[10:7],"b2",levels(df_stay$demo)[6:3],"b1",
                              levels(df_stay$demo)[2:1]),
                   labels=c("b8"="","b7"="","b6"="","b5"="","b4"="","b3"="","b2"="","b1"="")) +
  scale_y_continuous(breaks=c(0,25,50,75,100), limits = c(-25,100)) 
## Democratic Loyalists plot
p4 <- ggplot(df_never, aes(x=factor(demo, levels = rev(levels(factor(demo)))), y=TG_freq, fill = factor(col))) + 
  geom_bar(stat = "identity") + geom_text(aes(y=TG_freq/2, label=round(TG_freq)), color="black", size=2.5) +
  geom_errorbar(aes(ymin=TG_freq-sd, ymax=TG_freq+sd), width=.5) +
  scale_fill_manual(values = my.palette) + theme(legend.position="none",axis.ticks.y = element_blank()) + ylab("% identifying as each") + xlab("") +
  ggtitle("Democratic Loyalists") + coord_flip() + theme(plot.title = element_text(size=10), axis.text = element_text(size=8)) +
  scale_x_discrete(limits = c(levels(df_stay$demo)[37:31],"b8",levels(df_stay$demo)[30:26],"b7",
                              levels(df_stay$demo)[25:23],"b6",levels(df_stay$demo)[22:19],"b5",
                              levels(df_stay$demo)[18:15],"b4",levels(df_stay$demo)[14:11],"b3",
                              levels(df_stay$demo)[10:7],"b2",levels(df_stay$demo)[6:3],"b1",
                              levels(df_stay$demo)[2:1]),
                   labels=c("b8"="","b7"="","b6"="","b5"="","b4"="","b3"="","b2"="","b1"="")) +
  scale_y_continuous(breaks=c(0,25,50,75,100), limits = c(-25,100)) 
## breakdown of our sample 
d17sub <- subset(d17, stay_leave<=4)
t0 <- descr::freq(x=d17sub$stay_leave, w=d17sub$weight)[1:4,2]
df0 <- data.frame(matrix(c(4,2,3,1,t0,0,0,0,0),nrow=4,ncol=3))
names(df0) <- c("TG","TG_freq","x")
df0$TG <- as.factor(df0$TG)
df0$label_loc <- NA
df0$label_loc[df0$TG==1] <- df0$TG_freq[df0$TG==1]/2
df0$label_loc[df0$TG==3] <- df0$TG_freq[df0$TG==3]/2 + df0$TG_freq[df0$TG==1]
df0$label_loc[df0$TG==2] <- df0$TG_freq[df0$TG==2]/2 + df0$TG_freq[df0$TG==1] + df0$TG_freq[df0$TG==3]
df0$label_loc[df0$TG==4] <- df0$TG_freq[df0$TG==4]/2 + df0$TG_freq[df0$TG==1] + df0$TG_freq[df0$TG==2] + df0$TG_freq[df0$TG==3]
df0$N <- as.integer(table(d17sub$stay_leave))
df0$groupname <- c("Rep Loyalists","Rep\nSwitch","Dem\nSwitch","Dem Loyalists")
p5 <- ggplot(data=df0, aes(x=x, y=TG_freq, fill=factor(TG, levels = c("4","2","3","1")))) +
  geom_bar(stat="identity") +
  geom_text(aes(x=0.275,y=label_loc, label=groupname), color="black", size=2, fontface="bold") +
  geom_text(aes(x=-0.1,y=label_loc, label=paste(round(TG_freq),"%",sep="")), color="white", size=2) +
  geom_text(aes(x=-0.35,y=label_loc, label=N), color="white", size=2) +
  geom_text(aes(x=-0.35,y=-1, label="Unwtd N"), hjust=1,color="black", size=2) +
  geom_text(aes(x=-0.1,y=-1, label="Proportion"), hjust=1,color="black", size=2) +
  xlab("") + ylab("") + ylim(-9,100) +
  theme(legend.position="none",plot.title = element_text(hjust=0.5),
        panel.background = element_rect(fill = "white",colour = "white"),
        panel.border = element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.text.x = element_blank(), axis.ticks = element_blank(),
        axis.text.y = element_blank()) + 
  coord_flip() + scale_fill_manual(values = c("darkorange", alpha("darkorange", .45), alpha("purple3", .45), "purple3"))
### creating final plot of Figure H
p <- grid.arrange(p5, p1, p2, p4, p3, ncol=2,
                  layout_matrix = rbind(c(1,1),c(2,3),c(4,5)),
                  widths = c(2.5,2.5), heights = c(.4,2.6,2.75))
ggsave("online_appendix_c/plots/FigI_GroupProfile2017_CIs.png", p, width = 8, height = 10.5, units="in")

### creating individual plots for each Loyalist/Switcher group for Figure G
# removing error bars
## Republican Loyalists plot
p1 <- ggplot(df_stay, aes(x=factor(demo, levels = rev(levels(factor(demo)))), y=TG_freq, fill = factor(col))) + 
  geom_bar(stat = "identity") + geom_text(aes(y=TG_freq/2, label=round(TG_freq)), color="black", size=2.5) +
  #geom_errorbar(aes(ymin=TG_freq-sd, ymax=TG_freq+sd), width=.5) +
  scale_fill_manual(values = my.palette) + theme(legend.position="none",axis.ticks.y = element_blank()) + ylab("tk") + xlab("") +
  ggtitle("Republican Loyalists") + coord_flip() + theme(plot.title = element_text(size=10), axis.text = element_text(size=8), axis.title = element_text(color="white")) +
  scale_x_discrete(limits = c(levels(df_stay$demo)[37:31],"b8",levels(df_stay$demo)[30:26],"b7",
                              levels(df_stay$demo)[25:23],"b6",levels(df_stay$demo)[22:19],"b5",
                              levels(df_stay$demo)[18:15],"b4",levels(df_stay$demo)[14:11],"b3",
                              levels(df_stay$demo)[10:7],"b2",levels(df_stay$demo)[6:3],"b1",
                              levels(df_stay$demo)[2:1]),
                   labels=c("b8"="","b7"="","b6"="","b5"="","b4"="","b3"="","b2"="","b1"="")) +
  scale_y_continuous(breaks=c(0,25,50,75,100), limits = c(-25,100)) 
## Republican Switchers plot
p2 <- ggplot(df_leave, aes(x=factor(demo, levels = rev(levels(factor(demo)))), y=TG_freq, fill = factor(col))) + 
  geom_bar(stat = "identity") + geom_text(aes(y=TG_freq/2, label=round(TG_freq)), color="black", size=2.5) +
  #geom_errorbar(aes(ymin=TG_freq-sd, ymax=TG_freq+sd), width=.5) +
  scale_fill_manual(values = my.palette) + theme(legend.position="none",axis.ticks.y = element_blank()) + ylab("tk") + xlab("") +
  ggtitle("Republican Switchers") + coord_flip() + theme(plot.title = element_text(size=10), axis.text = element_text(size=8), axis.title = element_text(color="white")) +
  scale_x_discrete(limits = c(levels(df_stay$demo)[37:31],"b8",levels(df_stay$demo)[30:26],"b7",
                              levels(df_stay$demo)[25:23],"b6",levels(df_stay$demo)[22:19],"b5",
                              levels(df_stay$demo)[18:15],"b4",levels(df_stay$demo)[14:11],"b3",
                              levels(df_stay$demo)[10:7],"b2",levels(df_stay$demo)[6:3],"b1",
                              levels(df_stay$demo)[2:1]),
                   labels=c("b8"="","b7"="","b6"="","b5"="","b4"="","b3"="","b2"="","b1"="")) +
  scale_y_continuous(breaks=c(0,25,50,75,100), limits = c(-25,100)) 
## Democratic Switchers plot
p3 <- ggplot(df_join, aes(x=factor(demo, levels = rev(levels(factor(demo)))), y=TG_freq, fill = factor(col))) + 
  geom_bar(stat = "identity") + geom_text(aes(y=TG_freq/2, label=round(TG_freq)), color="black", size=2.5) +
  #geom_errorbar(aes(ymin=TG_freq-sd, ymax=TG_freq+sd), width=.5) +
  scale_fill_manual(values = my.palette) + theme(legend.position="none",axis.ticks.y = element_blank()) + ylab("% identifying as each") + xlab("") +
  ggtitle("Democratic Switchers") + coord_flip() + theme(plot.title = element_text(size=10), axis.text = element_text(size=8)) +
  scale_x_discrete(limits = c(levels(df_stay$demo)[37:31],"b8",levels(df_stay$demo)[30:26],"b7",
                              levels(df_stay$demo)[25:23],"b6",levels(df_stay$demo)[22:19],"b5",
                              levels(df_stay$demo)[18:15],"b4",levels(df_stay$demo)[14:11],"b3",
                              levels(df_stay$demo)[10:7],"b2",levels(df_stay$demo)[6:3],"b1",
                              levels(df_stay$demo)[2:1]),
                   labels=c("b8"="","b7"="","b6"="","b5"="","b4"="","b3"="","b2"="","b1"="")) +
  scale_y_continuous(breaks=c(0,25,50,75,100), limits = c(-25,100)) 
## Democratic Loyalists plot
p4 <- ggplot(df_never, aes(x=factor(demo, levels = rev(levels(factor(demo)))), y=TG_freq, fill = factor(col))) + 
  geom_bar(stat = "identity") + geom_text(aes(y=TG_freq/2, label=round(TG_freq)), color="black", size=2.5) +
  #geom_errorbar(aes(ymin=TG_freq-sd, ymax=TG_freq+sd), width=.5) +
  scale_fill_manual(values = my.palette) + theme(legend.position="none",axis.ticks.y = element_blank()) + ylab("% identifying as each") + xlab("") +
  ggtitle("Democratic Loyalists") + coord_flip() + theme(plot.title = element_text(size=10), axis.text = element_text(size=8)) +
  scale_x_discrete(limits = c(levels(df_stay$demo)[37:31],"b8",levels(df_stay$demo)[30:26],"b7",
                              levels(df_stay$demo)[25:23],"b6",levels(df_stay$demo)[22:19],"b5",
                              levels(df_stay$demo)[18:15],"b4",levels(df_stay$demo)[14:11],"b3",
                              levels(df_stay$demo)[10:7],"b2",levels(df_stay$demo)[6:3],"b1",
                              levels(df_stay$demo)[2:1]),
                   labels=c("b8"="","b7"="","b6"="","b5"="","b4"="","b3"="","b2"="","b1"="")) +
  scale_y_continuous(breaks=c(0,25,50,75,100), limits = c(-25,100)) 
### creating final plot of Figure G
g1 <- grid.arrange(p5, p1, p2, p4, p3, ncol=2,
                   layout_matrix = rbind(c(1,1),c(2,3),c(4,5)),
                   widths = c(2.5,2.5), heights = c(.4,2.6,2.75))
ggsave("online_appendix_c/plots/FigH_GroupProfile2017.png", g1, width = 8, height = 10.5, units="in")
rm(t0,p,p1,p2,p3,p4,p5,g1,my.palette,dsgn,df_never,df_join,df_leave,df_stay,df0,d17sub)


#### PREP FOR FIGURES J – M ####
## setting up datasets for plots
# subsetting datasets and standardizing scales
vars <- c("cosmo_scale2","american_scale_v1","american_scale_v2","taxes_scale_v1","laws_toofavorable","laws_toofavorable_wealthycorps", "trump_immig_app", #nativism
          "ECON_LADDER_past_future","ECON_LADDER_past_present","ECON_LADDER_present_future","personalfinance","PARENTS_rec","CHILDREN_rec", #economic anxiety (egocentric)
          "econ_wrongtrack","econ_strength", "country_wrongtrack","trump_disapp_econ","trump_disapp_stimjobs", #economic anxiety (sociotropic)
          "BREAK_RULES_rec","US_DARK_rec","COMPROMISE","taxes_scale_v2", #authoritarisnism
          "is_it_racist_scale1","is_it_racist_scale2", # racism
          "stay_leave","weight","RESPID")
d17.sub <- d17[vars]
x <- data.frame(sapply(c(1:24), function(i){scales::rescale(as.numeric(unlist(d17.sub[,i])), to = c(-1,1))}))
d17.sub <- cbind.data.frame(x,d17.sub[,25:27])
colnames(d17.sub) <- vars[c(1:24,25:27)]
d17_St_Lv <- subset(d17.sub, stay_leave==1 | stay_leave==2)
d17_Jo_Nv <- subset(d17.sub, stay_leave==3 | stay_leave==4)
# setting up survey designs
dsgn.stay <- svydesign(ids = ~RESPID, weights = ~weight, data = d17_St_Lv)
dsgn.never <- svydesign(ids = ~RESPID, weights = ~weight, data = d17_Jo_Nv)
# prep for plot DFs
rm(x,vars)
x <- c("Rep Loyalists","Rep Switchers","Dem Switchers","Dem Loyalists")

#### FIGURE J ####
## doing calculations for plots
# econ_wrongtrack
dsgn.stay.wr <- subset(dsgn.stay, !is.na(dsgn.stay$variables$econ_wrongtrack)) # dealing w/NAs
dsgn.never.wr <- subset(dsgn.never, !is.na(dsgn.never$variables$econ_wrongtrack)) # dealing w/NAs
y2 <- c(svyby(~econ_wrongtrack, ~ stay_leave, dsgn.stay.wr, svymean)$econ_wrongtrack,svyby(~econ_wrongtrack, ~ stay_leave, dsgn.never.wr, svymean)$econ_wrongtrack)
y2_error <- c(sqrt(svyby(~econ_wrongtrack, ~stay_leave, dsgn.stay.wr, svyvar)$econ_wrongtrack)/sqrt(nrow(dsgn.stay.wr)),sqrt(svyby(~econ_wrongtrack, ~stay_leave, dsgn.never.wr, svyvar)$econ_wrongtrack)/sqrt(nrow(dsgn.never.wr)))
# econ_strength 
y3 <- c(svyby(~econ_strength, ~ stay_leave, dsgn.stay, svymean)$econ_strength,svyby(~econ_strength, ~ stay_leave, dsgn.never, svymean)$econ_strength)
y3_error <- c(sqrt(svyby(~econ_strength, ~stay_leave, dsgn.stay, svyvar)$econ_strength)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~econ_strength, ~stay_leave, dsgn.never, svyvar)$econ_strength)/sqrt(nrow(d17_Jo_Nv)))
y3 <- y3*-1 # reversing scale
# country_wrongtrack 
dsgn.stay.tr <- subset(dsgn.stay, !is.na(dsgn.stay$variables$country_wrongtrack)) # dealing w/NAs
dsgn.never.tr <- subset(dsgn.never, !is.na(dsgn.never$variables$country_wrongtrack)) # dealing w/NAs
y4 <- c(svyby(~country_wrongtrack, ~ stay_leave, dsgn.stay.tr, svymean)$country_wrongtrack,svyby(~country_wrongtrack, ~ stay_leave, dsgn.never.tr, svymean)$country_wrongtrack)
y4_error <- c(sqrt(svyby(~country_wrongtrack, ~stay_leave, dsgn.stay.tr, svyvar)$country_wrongtrack)/sqrt(nrow(dsgn.stay.tr)),sqrt(svyby(~country_wrongtrack, ~stay_leave, dsgn.never.tr, svyvar)$country_wrongtrack)/sqrt(nrow(dsgn.never.tr)))
# trump_disapp_econ
y5 <- c(svyby(~trump_disapp_econ, ~ stay_leave, dsgn.stay, svymean)$trump_disapp_econ,svyby(~trump_disapp_econ, ~ stay_leave, dsgn.never, svymean)$trump_disapp_econ)
y5_error <- c(sqrt(svyby(~trump_disapp_econ, ~stay_leave, dsgn.stay, svyvar)$trump_disapp_econ)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~trump_disapp_econ, ~stay_leave, dsgn.never, svyvar)$trump_disapp_econ)/sqrt(nrow(d17_Jo_Nv)))
# trump_disapp_stimjobs 
y6 <- c(svyby(~trump_disapp_stimjobs, ~ stay_leave, dsgn.stay, svymean)$trump_disapp_stimjobs,svyby(~trump_disapp_stimjobs, ~ stay_leave, dsgn.never, svymean)$trump_disapp_stimjobs)
y6_error <- c(sqrt(svyby(~trump_disapp_stimjobs, ~stay_leave, dsgn.stay, svyvar)$trump_disapp_stimjobs)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~trump_disapp_stimjobs, ~stay_leave, dsgn.never, svyvar)$trump_disapp_stimjobs)/sqrt(nrow(d17_Jo_Nv)))
## combining calculations
df2 <- rbind.data.frame(cbind(x,y=y2,y_error=y2_error), cbind(x,y=y3,y_error=y3_error), cbind(x,y=y4,y_error=y4_error), cbind(x,y=y5,y_error=y5_error), cbind(x,y=y6,y_error=y6_error))
df2$y <- as.numeric(as.character(df2$y))
df2$y_error <- as.numeric(as.character(df2$y_error))
df2$measure <- c(rep("US economy is on wrong track",4),rep("US economy is very weak",4),rep("Country is on wrong track",4),rep("Disapprove of Trump on economy",4),rep("Disapprove of Trump on stimulating jobs",4))
colnames(df2) <- c("model","estimate","std.error","term")
# getting ordering by R Loyal - D Loyal difference
diffs <- data.frame(matrix(ncol = 2, nrow = length(unique(df2$term))))
names(diffs) <- c("term","diff")
diffs$term <- unique(df2$term)
for(i in 1:length(unique(df2$term))){
  subset <- subset(df2, term==unique(df2$term)[i])
  diffs[i,2] <- subset$estimate[subset$model=="Rep Loyalists"] - subset$estimate[subset$model=="Dem Loyalists"]
  }
diffs$rank <- rank(abs(diffs$diff))
diffs.sub <- subset(diffs, select = c("term","rank"))
df2 <- merge(df2, diffs.sub, by = "term")
df2 <- rbind.data.frame(df2[df2$rank==5,],df2[df2$rank==4,],df2[df2$rank==3,],df2[df2$rank==2,],df2[df2$rank==1,])
## plotting data
dwplot(df2, dodge_size = 0.4, dot_args=list(aes(colour = model, shape = model), size = 3), whisker_args=list(aes(colour = model))) + 
  theme_minimal() + xlab("Sociotropic economic anxiety (least to most)") + 
  theme(legend.title = element_blank(), legend.position = "top",legend.key.width = unit(.5,"cm"), 
        plot.title = element_text(size = 12), axis.title.x = element_text(size = 10), axis.text = element_text(size=10)) + 
  xlim(-1,1) + scale_colour_manual(breaks=c("Dem Loyalists","Dem Switchers","Rep Switchers","Rep Loyalists"), values= c("darkorange", alpha("darkorange", .45), alpha("purple3", .45), "purple3")) +
  scale_shape_manual(breaks=c("Dem Loyalists","Dem Switchers","Rep Switchers","Rep Loyalists"), values = c(20,20,20,20))
ggsave("online_appendix_c/plots/FigJ_econanxiety_socio_2017.png", width = 7.8, height = 4.25)
rm(df2,diffs,diffs.sub,subset,i,vars,
   dsgn.never.tr,dsgn.stay.tr,dsgn.never.wr,dsgn.stay.wr,
   y2,y2_error,y3,y3_error,y4,y4_error,y5,y5_error,y6,y6_error)

#### FIGURE K ####
## doing calculations for plots
# ECON_LADDER_past_future 
y2 <- c(svyby(~ECON_LADDER_past_future, ~ stay_leave, dsgn.stay, svymean)$ECON_LADDER_past_future,svyby(~ECON_LADDER_past_future, ~ stay_leave, dsgn.never, svymean)$ECON_LADDER_past_future)
y2_error <- c(sqrt(svyby(~ECON_LADDER_past_future, ~stay_leave, dsgn.stay, svyvar)$ECON_LADDER_past_future)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~ECON_LADDER_past_future, ~stay_leave, dsgn.never, svyvar)$ECON_LADDER_past_future)/sqrt(nrow(d17_Jo_Nv)))
# ECON_LADDER_past_present
y3 <- c(svyby(~ECON_LADDER_past_present, ~ stay_leave, dsgn.stay, svymean)$ECON_LADDER_past_present,svyby(~ECON_LADDER_past_present, ~ stay_leave, dsgn.never, svymean)$ECON_LADDER_past_present)
y3_error <- c(sqrt(svyby(~ECON_LADDER_past_present, ~stay_leave, dsgn.stay, svyvar)$ECON_LADDER_past_present)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~ECON_LADDER_past_present, ~stay_leave, dsgn.never, svyvar)$ECON_LADDER_past_present)/sqrt(nrow(d17_Jo_Nv)))
# ECON_LADDER_present_future
y4 <- c(svyby(~ECON_LADDER_present_future, ~ stay_leave, dsgn.stay, svymean)$ECON_LADDER_present_future,svyby(~ECON_LADDER_present_future, ~ stay_leave, dsgn.never, svymean)$ECON_LADDER_present_future)
y4_error <- c(sqrt(svyby(~ECON_LADDER_present_future, ~stay_leave, dsgn.stay, svyvar)$ECON_LADDER_present_future)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~ECON_LADDER_present_future, ~stay_leave, dsgn.never, svyvar)$ECON_LADDER_present_future)/sqrt(nrow(d17_Jo_Nv)))
# personalfinance
dsgn.stay.pf <- subset(dsgn.stay, !is.na(dsgn.stay$variables$personalfinance)) # dealing w/NAs
dsgn.never.pf <- subset(dsgn.never, !is.na(dsgn.never$variables$personalfinance)) # dealing w/NAs
y5 <- c(svyby(~personalfinance, ~ stay_leave, dsgn.stay.pf, svymean)$personalfinance,svyby(~personalfinance, ~ stay_leave, dsgn.never.pf, svymean)$personalfinance)
y5_error <- c(sqrt(svyby(~personalfinance, ~stay_leave, dsgn.stay.pf, svyvar)$personalfinance)/sqrt(nrow(dsgn.stay.pf)),sqrt(svyby(~personalfinance, ~stay_leave, dsgn.never.pf, svyvar)$personalfinance)/sqrt(nrow(dsgn.never.pf)))
y5 <- y5*-1 # reversing scale
# PARENTS_rec
dsgn.stay.par <- subset(dsgn.stay, !is.na(dsgn.stay$variables$PARENTS_rec)) # dealing w/NAs
dsgn.never.par <- subset(dsgn.never, !is.na(dsgn.never$variables$PARENTS_rec)) # dealing w/NAs
y6 <- c(svyby(~PARENTS_rec, ~ stay_leave, dsgn.stay.par, svymean)$PARENTS_rec,svyby(~PARENTS_rec, ~ stay_leave, dsgn.never.par, svymean)$PARENTS_rec)
y6_error <- c(sqrt(svyby(~PARENTS_rec, ~stay_leave, dsgn.stay.par, svyvar)$PARENTS_rec)/sqrt(nrow(dsgn.stay.par)),sqrt(svyby(~PARENTS_rec, ~stay_leave, dsgn.never.par, svyvar)$PARENTS_rec)/sqrt(nrow(dsgn.never.par)))
y6 <- y6*-1 # reversing scale
# CHILDREN_rec
dsgn.stay.ch <- subset(dsgn.stay, !is.na(dsgn.stay$variables$CHILDREN_rec)) # dealing w/NAs
dsgn.never.ch <- subset(dsgn.never, !is.na(dsgn.never$variables$CHILDREN_rec)) # dealing w/NAs
y7 <- c(svyby(~CHILDREN_rec, ~ stay_leave, dsgn.stay.ch, svymean)$CHILDREN_rec,svyby(~CHILDREN_rec, ~ stay_leave, dsgn.never.ch, svymean)$CHILDREN_rec)
y7_error <- c(sqrt(svyby(~CHILDREN_rec, ~stay_leave, dsgn.stay.ch, svyvar)$CHILDREN_rec)/sqrt(nrow(dsgn.stay.ch)),sqrt(svyby(~CHILDREN_rec, ~stay_leave, dsgn.never.ch, svyvar)$CHILDREN_rec)/sqrt(nrow(dsgn.never.ch)))
y7 <- y7*-1 # reversing scale
## combining calculations
df2 <- rbind.data.frame(cbind(x,y=y2,y_error=y2_error), cbind(x,y=y3,y_error=y3_error), cbind(x,y=y4,y_error=y4_error), cbind(x,y=y5,y_error=y5_error), cbind(x,y=y6,y_error=y6_error), cbind(x,y=y7,y_error=y7_error))
df2$y <- as.numeric(as.character(df2$y))
df2$y_error <- as.numeric(as.character(df2$y_error))
df2$measure <- c(rep("Family's finances as teen minus\nexpected of next gen",4),rep("Family's finances as teen\nminus current",4),rep("Current family finances minus\nexpected of next gen",4),rep("Personal financial situation is\ngetting worse",4),rep("Job opportunities for your children\nwill be worse",4),rep("Job opportunities for you worse\nthan parents'",4))
colnames(df2) <- c("model","estimate","std.error","term")
# getting ordering by R Loyal - D Loyal difference
diffs <- data.frame(matrix(ncol = 2, nrow = length(unique(df2$term))))
names(diffs) <- c("term","diff")
diffs$term <- unique(df2$term)
for(i in 1:length(unique(df2$term))){
  subset <- subset(df2, term==unique(df2$term)[i])
  diffs[i,2] <- subset$estimate[subset$model=="Rep Loyalists"] - subset$estimate[subset$model=="Dem Loyalists"]
  }
diffs$rank <- rank(abs(diffs$diff))
diffs.sub <- subset(diffs, select = c("term","rank"))
df2 <- merge(df2, diffs.sub, by = "term")
df2 <- rbind.data.frame(df2[df2$rank==6,],df2[df2$rank==5,],df2[df2$rank==4,],df2[df2$rank==3,],df2[df2$rank==2,],df2[df2$rank==1,])
## plotting data
dwplot(df2, dodge_size = 0.4, dot_args=list(aes(colour = model, shape = model), size = 3), whisker_args=list(aes(colour = model))) + 
  theme_minimal() + xlab("Personal economic anxiety (least to most)") + 
  theme(legend.title = element_blank(), legend.position = "top",legend.key.width = unit(.5,"cm"), 
        plot.title = element_text(size = 12), axis.title.x = element_text(size = 10), axis.text = element_text(size=10)) + 
  xlim(-1,1) + scale_colour_manual(breaks=c("Dem Loyalists","Dem Switchers","Rep Switchers","Rep Loyalists"), values= c("darkorange", alpha("darkorange", .45), alpha("purple3", .45), "purple3")) +
  scale_shape_manual(breaks=c("Dem Loyalists","Dem Switchers","Rep Switchers","Rep Loyalists"), values = c(20,20,20,20))
ggsave("online_appendix_c/plots/FigK_econanxiety_self_2017.png", width = 7.8, height = 4.6)
rm(df2,diffs,diffs.sub,subset,i,
   dsgn.never.ch,dsgn.stay.ch,dsgn.never.par,dsgn.stay.par,dsgn.never.pf,dsgn.stay.pf,
   y2,y2_error,y3,y3_error,y4,y4_error,y5,y5_error,y6,y6_error,y7,y7_error)

#### FIGURE L ####
## doing calculations for plots
# populism / taxes_scale_v2 
y5 <- c(svyby(~taxes_scale_v2, ~ stay_leave, dsgn.stay, svymean)$taxes_scale_v2,svyby(~taxes_scale_v2, ~ stay_leave, dsgn.never, svymean)$taxes_scale_v2)
y5_error <- c(sqrt(svyby(~taxes_scale_v2, ~stay_leave, dsgn.stay, svyvar)$taxes_scale_v2)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~taxes_scale_v2, ~stay_leave, dsgn.never, svyvar)$taxes_scale_v2)/sqrt(nrow(d17_Jo_Nv)))
y5 <- y5*-1 # reversing scale
# authoritarianism / BREAK_RULES_rec
y2 <- c(svyby(~BREAK_RULES_rec, ~ stay_leave, dsgn.stay, svymean)$BREAK_RULES_rec,svyby(~BREAK_RULES_rec, ~ stay_leave, dsgn.never, svymean)$BREAK_RULES_rec)
y2_error <- c(sqrt(svyby(~BREAK_RULES_rec, ~stay_leave, dsgn.stay, svyvar)$BREAK_RULES_rec)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~BREAK_RULES_rec, ~stay_leave, dsgn.never, svyvar)$BREAK_RULES_rec)/sqrt(nrow(d17_Jo_Nv)))
# COMPROMISE
y4 <- c(svyby(~COMPROMISE, ~ stay_leave, dsgn.stay, svymean)$COMPROMISE,svyby(~COMPROMISE, ~ stay_leave, dsgn.never, svymean)$COMPROMISE)
y4_error <- c(sqrt(svyby(~COMPROMISE, ~stay_leave, dsgn.stay, svyvar)$COMPROMISE)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~COMPROMISE, ~stay_leave, dsgn.never, svyvar)$COMPROMISE)/sqrt(nrow(d17_Jo_Nv)))
# Law favorability scale : wealthy people, large corporations
y6 <- c(svyby(~laws_toofavorable_wealthycorps, ~ stay_leave, dsgn.stay, svymean)$laws_toofavorable_wealthycorps,svyby(~laws_toofavorable_wealthycorps, ~ stay_leave, dsgn.never, svymean)$laws_toofavorable_wealthycorps)
y6 <- y6*-1 # reversing scale
y6_error <- c(sqrt(svyby(~laws_toofavorable_wealthycorps, ~stay_leave, dsgn.stay, svyvar)$laws_toofavorable_wealthycorps)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~laws_toofavorable_wealthycorps, ~stay_leave, dsgn.never, svyvar)$laws_toofavorable_wealthycorps)/sqrt(nrow(d17_Jo_Nv)))
## combining calculations
df2 <- rbind.data.frame(cbind(x,y=y6,y_error=y6_error),cbind(x,y=y5,y_error=y5_error), cbind(x,y=y2,y_error=y2_error), cbind(x,y=y4,y_error=y4_error))
df2$y <- as.numeric(as.character(df2$y))
df2$y_error <- as.numeric(as.character(df2$y_error))
df2$measure <- c(rep("Laws not favorable enough toward\nwealthy people, large corps",4),rep("Wealthy people, large corps receive less\nthan they contribute in taxes",4),rep("We need a leader willing to break rules",4),rep("More important for leader to stick to\nbeliefs than compromise",4))
colnames(df2) <- c("model","estimate","std.error","term")
# getting ordering by R Loyal - D Loyal difference
diffs <- data.frame(matrix(ncol = 2, nrow = length(unique(df2$term))))
names(diffs) <- c("term","diff")
diffs$term <- unique(df2$term)
for(i in 1:length(unique(df2$term))){
  subset <- subset(df2, term==unique(df2$term)[i])
  diffs[i,2] <- subset$estimate[subset$model=="Rep Loyalists"] - subset$estimate[subset$model=="Dem Loyalists"]
  }
diffs$rank <- rank(diffs$diff)
diffs.sub <- subset(diffs, select = c("term","rank"))
df2 <- merge(df2, diffs.sub, by = "term")
df2 <- rbind.data.frame(df2[df2$rank==4,],df2[df2$rank==3,],df2[df2$rank==2,],df2[df2$rank==1,])
## plotting data
dwplot(df2, dodge_size = 0.4, dot_args=list(aes(colour = model, shape = model), size = 3), whisker_args=list(aes(colour = model))) + 
  theme_minimal() + xlab("Disagree to Agree") + 
  theme(legend.title = element_blank(), legend.position = "top",legend.key.width = unit(.5,"cm"), 
        plot.title = element_text(size = 12), axis.title.x = element_text(size = 10), axis.text = element_text(size=10)) + 
  xlim(-1,1) + scale_colour_manual(breaks=c("Dem Loyalists","Dem Switchers","Rep Switchers","Rep Loyalists"), values= c("darkorange", alpha("darkorange", .45), alpha("purple3", .45), "purple3")) +
  scale_shape_manual(breaks=c("Dem Loyalists","Dem Switchers","Rep Switchers","Rep Loyalists"), values = c(20,20,20,20))
ggsave("online_appendix_c/plots/FigL_governance_styles_2017.png", width = 7.8, height = 3.3)
rm(df2,diffs,diffs.sub,subset,i,y2,y2_error,y4,y4_error,y5,y5_error,y6,y6_error)

#### FIGURE M ####
## doing calculations for plots
# cosmopolitanism scale
y2 <- c(svyby(~cosmo_scale2, ~ stay_leave, dsgn.stay, svymean)$cosmo_scale2,svyby(~cosmo_scale2, ~ stay_leave, dsgn.never, svymean)$cosmo_scale2)
y2 <- y2*-1 # reversing scale
y2_error <- c(sqrt(svyby(~cosmo_scale2, ~stay_leave, dsgn.stay, svyvar)$cosmo_scale2)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~cosmo_scale2, ~stay_leave, dsgn.never, svyvar)$cosmo_scale2)/sqrt(nrow(d17_Jo_Nv)))
# Truly American scale v1
y3 <- c(svyby(~american_scale_v1, ~ stay_leave, dsgn.stay, svymean)$american_scale_v1,svyby(~american_scale_v1, ~ stay_leave, dsgn.never, svymean)$american_scale_v1)
y3_error <- c(sqrt(svyby(~american_scale_v1, ~stay_leave, dsgn.stay, svyvar)$american_scale_v1)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~american_scale_v1, ~stay_leave, dsgn.never, svyvar)$american_scale_v1)/sqrt(nrow(d17_Jo_Nv)))
# Truly American scale v2 
y4 <- c(svyby(~american_scale_v2, ~ stay_leave, dsgn.stay, svymean)$american_scale_v2,svyby(~american_scale_v2, ~ stay_leave, dsgn.never, svymean)$american_scale_v2)
y4_error <- c(sqrt(svyby(~american_scale_v2, ~stay_leave, dsgn.stay, svyvar)$american_scale_v2)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~american_scale_v2, ~stay_leave, dsgn.never, svyvar)$american_scale_v2)/sqrt(nrow(d17_Jo_Nv)))
# Taxes scale v1 
y5 <- c(svyby(~taxes_scale_v1, ~ stay_leave, dsgn.stay, svymean)$taxes_scale_v1,svyby(~taxes_scale_v1, ~ stay_leave, dsgn.never, svymean)$taxes_scale_v1)
y5_error <- c(sqrt(svyby(~taxes_scale_v1, ~stay_leave, dsgn.stay, svyvar)$taxes_scale_v1)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~taxes_scale_v1, ~stay_leave, dsgn.never, svyvar)$taxes_scale_v1)/sqrt(nrow(d17_Jo_Nv)))
# Law favorability scale : blacks, hispanics, illegal immigrants 
y6 <- c(svyby(~laws_toofavorable, ~ stay_leave, dsgn.stay, svymean)$laws_toofavorable,svyby(~laws_toofavorable, ~ stay_leave, dsgn.never, svymean)$laws_toofavorable)
y6_error <- c(sqrt(svyby(~laws_toofavorable, ~stay_leave, dsgn.stay, svyvar)$laws_toofavorable)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~laws_toofavorable, ~stay_leave, dsgn.never, svyvar)$laws_toofavorable)/sqrt(nrow(d17_Jo_Nv)))
# Approval on Trump's job w/immigration / trump_immig_app
y7 <- c(svyby(~trump_immig_app, ~ stay_leave, dsgn.stay, svymean)$trump_immig_app,svyby(~trump_immig_app, ~ stay_leave, dsgn.never, svymean)$trump_immig_app)
y7 <- y7*-1 # reversing scale 
y7_error <- c(sqrt(svyby(~trump_immig_app, ~stay_leave, dsgn.stay, svyvar)$trump_immig_app)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~trump_immig_app, ~stay_leave, dsgn.never, svyvar)$trump_immig_app)/sqrt(nrow(d17_Jo_Nv)))
# is it racist 1 - country better in past, people should speak English, voting for Trump, it's for good reason when police shoot civilians
y9 <- c(svyby(~is_it_racist_scale1, ~ stay_leave, dsgn.stay, svymean)$is_it_racist_scale1,svyby(~is_it_racist_scale1, ~ stay_leave, dsgn.never, svymean)$is_it_racist_scale1)
y9_error <- c(sqrt(svyby(~is_it_racist_scale1, ~stay_leave, dsgn.stay, svyvar)$is_it_racist_scale1)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~is_it_racist_scale1, ~stay_leave, dsgn.never, svyvar)$is_it_racist_scale1)/sqrt(nrow(d17_Jo_Nv)))
# is it racist 2 - telling joke about racial group, using offensive word for racial group
y10 <- c(svyby(~is_it_racist_scale2, ~ stay_leave, dsgn.stay, svymean)$is_it_racist_scale2,svyby(~is_it_racist_scale2, ~ stay_leave, dsgn.never, svymean)$is_it_racist_scale2)
y10_error <- c(sqrt(svyby(~is_it_racist_scale2, ~stay_leave, dsgn.stay, svyvar)$is_it_racist_scale2)/sqrt(nrow(d17_St_Lv)),sqrt(svyby(~is_it_racist_scale2, ~stay_leave, dsgn.never, svyvar)$is_it_racist_scale2)/sqrt(nrow(d17_Jo_Nv)))
## combining calculations
df2 <- rbind.data.frame(cbind(x,y=y2,y_error=y2_error), cbind(x,y=y3,y_error=y3_error), cbind(x,y=y4,y_error=y4_error), cbind(x,y=y5,y_error=y5_error), cbind(x,y=y6,y_error=y6_error), cbind(x,y=y7,y_error=y7_error),
                        cbind(x,y=y9,y_error=y9_error), cbind(x,y=y10,y_error=y10_error))
df2$y <- as.numeric(as.character(df2$y))
df2$y_error <- as.numeric(as.character(df2$y_error))
df2$measure <- c(rep("Cosmopolitanism",4),rep("Truly American if feel American,\nhave citizenship, respect institutions",4),rep("Truly American if born in US, lived in US\nmost of life, are Christian",4),
                 rep("Blacks, Hispanics, illegal immigrants receive\nmore than contribute in taxes",4),rep("Laws too favorable toward\nblacks, Hispanics, illegal immigrants",4),
                 rep("Disapproval of Trump handling immigration",4),rep("Not racist to say country better in past, people in\nU.S. should speak English; vote for Trump; agree\nwhen police shoot civilians, it's for good reason", 4),
                 rep("Not racist to tell joke about racial group,\nuse offensive word for racial group",4))
colnames(df2) <- c("model","estimate","std.error","term")
# getting ordering by R Loyal - D Loyal difference
diffs <- data.frame(matrix(ncol = 2, nrow = length(unique(df2$term))))
names(diffs) <- c("term","diff")
diffs$term <- unique(df2$term)
for(i in 1:length(unique(df2$term))){
  subset <- subset(df2, term==unique(df2$term)[i])
  diffs[i,2] <- subset$estimate[subset$model=="Rep Loyalists"] - subset$estimate[subset$model=="Dem Loyalists"]
  }
diffs$rank <- rank(diffs$diff)
diffs.sub <- subset(diffs, select = c("term","rank"))
df2 <- merge(df2, diffs.sub, by = "term")
df2 <- rbind.data.frame(df2[df2$rank==8,],df2[df2$rank==7,],df2[df2$rank==6,],df2[df2$rank==5,],df2[df2$rank==4,],df2[df2$rank==3,],df2[df2$rank==2,],df2[df2$rank==1,])
## plotting data
dwplot(df2, dodge_size = 0.4, dot_args=list(aes(colour = model, shape = model), size = 3), whisker_args=list(aes(colour = model))) + 
  theme_minimal() + xlab("Left to Right") + 
  theme(legend.title = element_blank(), legend.position = "top",legend.key.width = unit(.5,"cm"), 
        plot.title = element_text(size = 12), axis.title.x = element_text(size = 10), axis.text = element_text(size=10)) + 
  xlim(-1,1) + scale_colour_manual(breaks=c("Dem Loyalists","Dem Switchers","Rep Switchers","Rep Loyalists"), values= c("darkorange", alpha("darkorange", .45), alpha("purple3", .45), "purple3")) +
  scale_shape_manual(breaks=c("Dem Loyalists","Dem Switchers","Rep Switchers","Rep Loyalists"), values = c(20,20,20,20))
ggsave("online_appendix_c/plots/FigM_nativism_and_racism_2017.png", width = 7.8, height = 6)
rm(df2,diffs,diffs.sub,subset,i,x,y2,y2_error,y3,y3_error,y4,y4_error,y5,y5_error,
   y6,y6_error,y7,y7_error,y9,y9_error,y10,y10_error)